package org.phalanx.gwt.client;

import org.phalanx.gwt.client.constants.PhalanxPagenameConstants;
import org.phalanx.gwt.client.screens.ContextPanelChooser;
import org.phalanx.gwt.client.screens.GameScreen;
import org.phalanx.gwt.client.screens.MainScreen;
import org.phalanx.gwt.client.screens.TopLinkPanel;
import org.phalanx.gwt.client.shared.AuthenticationListener;
import org.phalanx.gwt.client.shared.AuthenticationManager;
import org.phalanx.gwt.client.shared.MessageListener;
import org.phalanx.gwt.client.shared.MessageManager;
import org.phalanx.gwt.client.shared.ServerMessage;

import com.google.gwt.core.client.EntryPoint;
import com.google.gwt.core.client.GWT;
import com.google.gwt.dom.client.Document;
import com.google.gwt.event.dom.client.ClickEvent;
import com.google.gwt.event.dom.client.ClickHandler;
import com.google.gwt.event.dom.client.KeyCodes;
import com.google.gwt.event.dom.client.KeyPressEvent;
import com.google.gwt.event.dom.client.KeyPressHandler;
import com.google.gwt.http.client.RequestBuilder;
import com.google.gwt.http.client.RequestException;
import com.google.gwt.user.client.Window;
import com.google.gwt.user.client.ui.AbsolutePanel;
import com.google.gwt.user.client.ui.Button;
import com.google.gwt.user.client.ui.HorizontalPanel;
import com.google.gwt.user.client.ui.ListBox;
import com.google.gwt.user.client.ui.RootPanel;
import com.google.gwt.user.client.ui.TextArea;
import com.google.gwt.user.client.ui.TextBox;
import com.google.gwt.user.client.ui.VerticalPanel;
import com.google.gwt.widgetideas.client.GlassPanel;

public class PhalanxWebClient implements EntryPoint, AuthenticationListener, MessageListener, ClickHandler {
	private static final Integer majorVersion = 0;
	private static final Integer minorVersion = 1;
	private static final Integer subVersion = 0;
	private AuthenticationManager auth;
	private MessageManager msgMgr;
	private TextArea incomingTestArea = new TextArea();
	private TextBox msgTxtBox = new TextBox();
	private Button testMsgButton = new Button("Send Message");
	private Button joinChat = new Button("Click to Join Chat");
	private ListBox userList = new ListBox();
	private MainScreen contextPanel;
	private ContextPanelChooser chooser;
	private TopLinkPanel menuPanel;
	
	public static final String WorkingTitle = "Phalanx Alpha";

	@Override
	public void onModuleLoad() {
		Document.get().setTitle(WorkingTitle + " " + getVersionString());
		// Check if auth cookie is valid
		// This prevents the web client from being hit directly without
		// having being registered
		
		auth = new AuthenticationManager(this);
		auth.sendLoginRequest();
	}
	
	public String getVersionString(){
		return majorVersion + "." + minorVersion + "." + subVersion;
	}
	
	private void startPhalanxWebClient(){
		try {
			setupMsgManager();
			chooser = new ContextPanelChooser(RootPanel.get("main")); // Chooser for the <div id = "main">

			setUpPermanentPanel();
			
			chooser.addPanelToChooser("home", contextPanel);
			
			RootPanel.get("menu").add(menuPanel);
			chooser.setContextPanel("home");
			
			
		} catch (RequestException re){
			Window.alert("Cannot connect to live data feed");
		}
	}
	
	private void setUpPermanentPanel(){
		menuPanel = new TopLinkPanel(chooser, msgMgr);
		menuPanel.init();
		
		contextPanel = new MainScreen(chooser, msgMgr);
		
	}
	
	private void setupMsgManager() throws RequestException{
		msgMgr = new MessageManager();
		msgMgr.addMessageListener("test", this);
		msgMgr.addMessageListener("chat", this);
		msgMgr.initializeFeed();
		msgMgr.setFeedTimer();
		
	}

	@Override
	public void authCallBack(boolean isLoggedIn, Integer status) {
		if (!isLoggedIn){
			Window.Location.assign(GWT.getHostPageBaseURL() + PhalanxPagenameConstants.LOGIN_PAGE);
		}else {
			startPhalanxWebClient();
		}
	}

	@Override
	public void onMessageReceived(ServerMessage msg) {
		// TODO Auto-generated method stub
		if (msg.getContext().equals("test")){
			incomingTestArea.setText(incomingTestArea.getText() + "\n" + msg.getMessageContentsValue("a"));
		}
		else if (msg.getContext().equals("chat")){
			if (msg.getMessageContentsValue("type").equals("msg")){
				String msgString = msg.getMessageContentsValue("sender") + ": " + msg.getMessageContentsValue("msg");
				incomingTestArea.setText(incomingTestArea.getText() + "\n" + msgString);
			}
			else if (msg.getMessageContentsValue("type").equals("status")){
				if (msg.getMessageContentsValue("status").equals("userlist")){
					userList.clear();
					String[] userListString = msg.getMessageContentsValue("userlist").split(":");

					for (int i = 0; i < userListString.length; i++){
						userList.addItem(userListString[i]);
					}
				}
				else if (msg.getMessageContentsValue("status").equals("userjoined")){
					String newUser = msg.getMessageContentsValue("userlist");
					userList.addItem(newUser);
					appendToChatWindow(newUser + " has joined ");
				}
				else if (msg.getMessageContentsValue("status").equals("userleft")){
					String newUser = msg.getMessageContentsValue("userlist");

					for (int i = 0; i < userList.getItemCount(); i++){
						String listData = userList.getItemText(i);
						if (listData.equals(newUser))
							userList.removeItem(i);
						break;
					}
					
					appendToChatWindow(newUser + " has left ");
				}
			} 
		}
	}
	
	
	public void appendToChatWindow(String text){
		incomingTestArea.setText(incomingTestArea.getText() + "\n" + text);
	}

	@Override
	public void onClick(ClickEvent event) {
		if (event.getSource().equals(testMsgButton)){
			sendTestMessage();
		}
		else if (event.getSource().equals(joinChat)){
			joinChat();
		}
	}
	
	public void sendTestMessage(){
/*		ServerMessage msg = new ServerMessage();
		msg.setContext("test");
		msg.addMessageContents("a", msgTxtBox.getText());
		msgTxtBox.setText("");

		msgMgr.sendMessage(msg);*/
		
		ServerMessage msg = new ServerMessage();
		msg.setPOST();
		msg.setContext("chat");
		msg.addMessageContents("type", "msg");
		msg.addMessageContents("chatroom", "TestChat");
		msg.addMessageContents("msg", msgTxtBox.getText());
		msgTxtBox.setText("");
		
		msgMgr.sendMessage(msg);
	}
	
	public void joinChat(){
		ServerMessage msg = new ServerMessage();
		msg.setPOST();
		msg.setContext("chat");
		msg.addMessageContents("type", "command");
		msg.addMessageContents("command", "join");
		msg.addMessageContents("chatroom", "TestChat");
		
		msgMgr.sendMessage(msg);
	}

}
